package org.example.homework.service.impl;

import org.example.homework.entity.CartItem;
import org.example.homework.mapper.CartMapper;
import org.example.homework.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Override
    public void addToCart(Integer userId, Integer productId, Integer quantity) {
        // 检查购物车中是否已存在该商品
        CartItem existingItem = cartMapper.findByUserIdAndProductId(userId, productId);
        
        if (existingItem != null) {
            // 如果已存在，更新数量
            cartMapper.updateQuantity(existingItem.getId(), existingItem.getQuantity() + quantity);
        } else {
            // 如果不存在，添加新项
            CartItem cartItem = new CartItem();
            cartItem.setUserId(userId);
            cartItem.setProductId(productId);
            cartItem.setQuantity(quantity);
            cartMapper.insert(cartItem);
        }
    }

    @Override
    public List<CartItem> getCartItems(Integer userId) {
        System.out.println("getCartItems"+ cartMapper.findByUserId(userId));
        return cartMapper.findByUserId(userId);
    }

    @Override
    public void removeFromCart(Integer itemId, Integer userId) {
        System.out.println("removeFromCart"+ itemId);
        cartMapper.deleteByIdAndUserId(itemId, userId);
    }

    @Override
    public void updateQuantity(Integer itemId, Integer userId, Integer quantity) {
        cartMapper.updateQuantity(itemId, quantity);
    }
} 